<template>
  <!-- 新增/修改 -->
  <el-dialog
    v-model="dialogVisible"
    title="用户角色分配"
    @closed="closedDialog"
    width="30%"
    :close-on-click-modal="false"
  >
    <el-table
      ref="roleRef"
      :data="roleData"
      row-key="id"
      border
      @select="handleUserRole"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" prop="roleName" />
      <el-table-column align="center" label="角色名称" prop="roleName" />
      <el-table-column align="center" label="角色编码" prop="roleCode" />
    </el-table>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onBeforeMount } from "vue";
import UserAPI from "@/api/system/base/user";
import RoleAPI from "@/api/system/sys/role";
import { ElTable } from "element-plus";

/**
 * 用户角色配置
 */
defineOptions({
  name: "EditUserRoleDialog",
});
const props = defineProps({
  userId: {
    type: String,
    required: true,
  },
  closedDialog: {
    type: Function,
    required: true,
  },
});

/** 角色列表 */
const roleData = ref<any>();
// Map对象数据格式：roleCode:roleTree[xx]
const selectRoleTemp = ref<any>({});
const roleRef = ref<InstanceType<typeof ElTable>>();
const dialogVisible = ref<boolean>(true);
const loading = ref<boolean>(false);

/** 配置角色 */
const handleUserRole = (selection: any) => {
  const roles = [];
  for (const role of selection) {
    roles.push(role.roleCode);
  }
  UserAPI.setUserRoleApi(props.userId, { roleCodes: roles })
    .then((res) => {
      const { status } = res;
      if (status === 200) {
        ElMessage.success("角色更新成功");
      }
    })
    .finally(() => {
      loading.value = false;
      props.closedDialog();
    });
};

/** 关闭弹窗 */
const closedDialog = () => {
  props.closedDialog(false);
};

/** 生成角色map对象，格式roleCode:roleTree[xx]  */
const generateRoleMap = (data: any) => {
  data.forEach((item: any) => {
    selectRoleTemp.value[item.roleCode] = item;
  });
};

/** 页面渲染完成后初始化 */
onBeforeMount(async () => {
  loading.value = true;
  if (props.userId) {
    // 获取系统角色
    await RoleAPI.getSysRoleListApi({
      limit: 200,
    }).then((res) => {
      const { data } = res;
      // 页面中缓存角色
      roleData.value = data.rows;
      // 转换为map存储
      generateRoleMap(data.rows);
    });
    // 获取用户已有角色
    await UserAPI.getUserRolesByUserIdApi(props.userId)
      .then((res) => {
        const roleList = res.data;
        if (roleList) {
          roleList.forEach((row: any) => {
            const role = selectRoleTemp.value[row];
            if (role) {
              roleRef.value?.toggleRowSelection(role, true);
            }
          });
        }
      })
      .finally(() => {
        loading.value = false;
      });
  }
});
</script>

<style lang="scss" scoped></style>
